package com.candy.blog.service.imp;

import com.candy.blog.NotFoundException;
import com.candy.blog.dao.TypeRepository;
import com.candy.blog.pojo.Type;
import com.candy.blog.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @version 1.0
 * @author: 南风
 * @description
 * @date: 2022/2/12 16:39
 */
@Service
public class TypeServiceImp implements TypeService {
    @Autowired
    private TypeRepository typeRepository;

    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {
        return typeRepository.findOne(id);
    }

    @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);
    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        // 先根据id查找类型
        Type t = typeRepository.findOne(id);
        // 如果该类型不存在，则抛出异常
        if (t == null) {
            throw new NotFoundException("不存在该类型");
        }
        // 如果该资源存在，将数据放到t中，返回。
        // args1：source(想要复制的资源),args2：target(复制给哪个目标对象)
        BeanUtils.copyProperties(type, t);
        return typeRepository.save(t);
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeRepository.delete(id);
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }
}
